package cn.sise.edu.crm.shiro;

import cn.sise.edu.crm.domain.Employee;
import cn.sise.edu.crm.service.IEmployeeService;
import cn.sise.edu.crm.service.IPermissionService;
import cn.sise.edu.crm.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.List;

/**
 * Created by chen on 2019/11/9.
 */
public class EmployeeRealm extends AuthorizingRealm {


    private IEmployeeService employeeService;
    public void  setEmployeeService(IEmployeeService employeeService){
        this.employeeService=employeeService;
    }

    private IRoleService roleService;
    public void setRoleService(IRoleService roleService) {
        this.roleService = roleService;
    }

    private IPermissionService permissionService;
    public void setPermissionService(IPermissionService permissionService) {
        this.permissionService = permissionService;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String username = upToken.getUsername();
        Employee employee = employeeService.selectByUsename(username);
        //UserContext.setEmployee(employee);
        if (employee == null) {
            return null;
        }
        return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()) ,this.getName());

    }
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        if (employee.isAdmin()){
            info.addRole(employee.getName());
            info.addStringPermission("*:*");
            return info;
        }
        List<String> roles = roleService.selectByEmployee(employee.getId());
        List<String> permissioins = permissionService.selectByEmployeeId(employee.getId());
        info.addRoles(roles);
        info.addStringPermissions(permissioins);
        return info;
    }
}
